<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的个人资料 - VideoWeb</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="/css/style.css">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script type="importmap">
    {
      "imports": {
        "vue": "https://unpkg.com/vue@3/dist/vue.esm-browser.js"
      }
    }
    </script>
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
            <div class="container">
                <a class="navbar-brand" href="/">
                    <i class="fas fa-play-circle"></i> Video Danmaku
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNav">
                    <ul class="navbar-nav me-auto">
                        <li class="nav-item">
                            <a class="nav-link" href="/"><i class="fas fa-home"></i> 首页</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/upload.html"><i class="fas fa-upload"></i> 投稿</a>
                        </li>
                    </ul>
                    <ul class="navbar-nav">
                        <li class="nav-item">
                            <a class="nav-link active" href="/profile.html">
                                <i class="fas fa-user"></i> 个人中心
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#" @click="handleLogout">
                                <i class="fas fa-sign-out-alt"></i> 退出登录
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>

        <div v-if="!authLoading && isAuthenticated" id="pageContent">
            <div class="container mt-4">
                <div class="row">
                    <div class="col-md-4">
                        <div class="card mb-4">
                            <div class="card-body">
                                <h5 class="card-title"><i class="fas fa-user-circle"></i> 个人信息</h5>
                                <div class="mt-3">
                                    <div class="user-info-item mb-3">
                                        <i class="fas fa-user text-primary"></i>
                                        <strong> 用户名：</strong> {{ currentUser?.username }}
                                    </div>
                                    <div class="user-info-item mb-3">
                                        <i class="fas fa-envelope text-primary"></i>
                                        <strong> 邮箱：</strong> {{ currentUser?.email || '未设置' }}
                                    </div>
                                    <div class="user-info-item mb-3">
                                        <i class="fas fa-video text-primary"></i>
                                        <strong> 视频总数：</strong> {{ videoCount }}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-8">
                        <div class="card">
                            <div class="card-body">
                                <h5 class="card-title"><i class="fas fa-video"></i> 我的视频</h5>
                                <div class="row mt-3">
                                    <div v-if="loadingVideos" class="col-12 text-center">
                                        <div class="spinner-border text-primary" role="status">
                                            <span class="visually-hidden">Loading...</span>
                                        </div>
                                        <p class="mt-2">正在加载视频...</p>
                                    </div>
                                    <div v-else-if="videos.length === 0" class="col-12">
                                        <div class="text-center py-5">
                                            <i class="fas fa-video fa-3x text-muted mb-3"></i>
                                            <p class="text-muted">您还没有上传任何视频</p>
                                            <a href="/upload.html" class="btn btn-primary">立即上传</a>
                                        </div>
                                    </div>
                                    <div v-else v-for="video in videos" :key="video.id" class="col-md-6 col-lg-4 mb-4">
                                        <div class="card h-100">
                                            <div class="video-thumbnail position-relative">
                                                <img :src="`/api/videos/${video.id}/thumbnail`" 
                                                     :alt="video.title" 
                                                     class="card-img-top"
                                                     style="height: 200px; object-fit: cover;"
                                                     @error="handleImageError">
                                                <span v-if="video.duration" class="video-duration position-absolute bottom-0 end-0 m-2 px-2 py-1 bg-dark text-white rounded">
                                                    {{ formatDuration(video.duration) }}
                                                </span>
                                            </div>
                                            <div class="card-body">
                                                <h5 class="card-title text-truncate">{{ video.title }}</h5>
                                                <p class="card-text small text-muted">
                                                    上传时间：{{ formatDate(video.uploadTime || video.createTime) }}
                                                </p>
                                                <p class="card-text small">{{ video.description || '暂无描述' }}</p>
                                            </div>
                                            <div class="card-footer bg-transparent">
                                                <div class="btn-group w-100">
                                                    <a :href="`/player.html?id=${video.id}`" class="btn btn-primary btn-sm">
                                                        <i class="fas fa-play"></i> 播放
                                                    </a>
                                                    <button @click="deleteVideo(video.id)" class="btn btn-danger btn-sm">
                                                        <i class="fas fa-trash"></i> 删除
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div v-if="authLoading" class="text-center mt-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-2">正在验证身份...</p>
        </div>

        <div v-if="!authLoading && !isAuthenticated" class="text-center mt-5">
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i>
                认证检查失败，即将跳转到登录页面...
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script type="module">
        import { createApp, ref, computed, onMounted } from 'vue';
        import { authState, checkAuthStatus, logout, showToast } from '/js/auth.js';

        createApp({
            setup() {
                const authLoading = ref(true);
                const loadingVideos = ref(false);
                const videos = ref([]);

                // Auth computed properties
                const isAuthenticated = computed(() => authState.isAuthenticated);
                const currentUser = computed(() => authState.currentUser);
                const videoCount = computed(() => videos.value.length);

                // Load user's videos
                const loadUserVideos = async () => {
                    if (!currentUser.value) return;

                    loadingVideos.value = true;
                    try {
                        const response = await axios.get('/api/videos/user');

                        if (!response.data || response.data.length === 0) {
                            videos.value = [];
                            return;
                        }

                        videos.value = response.data;

                    } catch (error) {
                        console.error('Failed to load videos:', error);
                        videos.value = [];
                        showToast('加载视频失败，请刷新页面重试', 'error');
                    } finally {
                        loadingVideos.value = false;
                    }
                };

                // Delete video
                const deleteVideo = async (videoId) => {
                    if (!confirm('确定要删除这个视频吗？删除后无法恢复！')) {
                        return;
                    }

                    try {
                        await axios.delete(`/api/videos/${videoId}`);
                        
                        // Show success message
                        showToast('视频删除成功！', 'success');
                        
                        // Reload the videos list
                        await loadUserVideos();
                    } catch (error) {
                        console.error('Failed to delete video:', error);
                        if (error.response && error.response.status === 404) {
                            showToast('视频未找到或您没有权限删除此视频', 'error');
                        } else if (error.response && error.response.status === 401) {
                            showToast('请先登录', 'error');
                            window.location.href = '/login.html?redirect=/profile.html';
                        } else {
                            showToast('删除视频失败，请稍后重试', 'error');
                        }
                    }
                };

                // Handle logout
                const handleLogout = async (event) => {
                    event.preventDefault();
                    await logout();
                };

                // Utility functions
                const formatDuration = (seconds) => {
                    if (!seconds) return '0:00';
                    const minutes = Math.floor(seconds / 60);
                    const remainingSeconds = Math.floor(seconds % 60);
                    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
                };

                const formatDate = (dateString) => {
                    if (!dateString) return '';
                    const date = new Date(dateString);
                    return new Intl.DateTimeFormat('en-US', { 
                        year: 'numeric', 
                        month: 'short', 
                        day: 'numeric' 
                    }).format(date);
                };

                const handleImageError = (event) => {
                    event.target.src = '';
                };

                // Lifecycle
                onMounted(async () => {
                    console.log('Profile page: Starting authentication check...');
                    
                    try {
                        // Check authentication status with server
                        console.log('Validating authentication with server...');
                        const isAuth = await checkAuthStatus(true);
                        console.log('Auth status result:', isAuth);
                        
                        if (!isAuth) {
                            console.log('Authentication failed, redirecting to login');
                            window.location.href = '/login.html?redirect=/profile.html';
                            return;
                        }
                        
                        console.log('Authentication successful, showing page content');
                        authLoading.value = false;
                        
                        // Load user's videos
                        await loadUserVideos();
                        
                    } catch (error) {
                        console.error('Auth check failed with error:', error);
                        authLoading.value = false;
                        setTimeout(() => {
                            window.location.href = '/login.html?redirect=/profile.html';
                        }, 2000);
                    }
                });

                return {
                    authLoading,
                    loadingVideos,
                    videos,
                    isAuthenticated,
                    currentUser,
                    videoCount,
                    loadUserVideos,
                    deleteVideo,
                    handleLogout,
                    formatDuration,
                    formatDate,
                    handleImageError
                };
            }
        }).mount('#app');
    </script>
</body>
</html>
